/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.movil;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import negocio.GestorFotosLocal;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author Ing. Monica Merlo, Ing. Agustin  Fernandez
 */
public class SubirFotoAppMovilServlet extends HttpServlet {

    static Logger logger = Logger.getLogger(SubirFotoAppMovilServlet.class);

    public static void log4jArchivo (Exception e){
        /**
         * Primero obtenemos la url del archivo de configuración,
         * como están en el mismo paquete que la clase Main lo podemos obtener con el método getResource().
         */
        URL url = SubirFotoAppMovilServlet.class.getResource("/configuracion/log4j.properties");
        /**
         * Despues cargamos el archivo de configuración
         */
        PropertyConfigurator.configure(url);
        logger.error(e);
    }

    @EJB(name = "GestorFotosBean")
    private GestorFotosLocal gestorFotosBean;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String exitoSubida = "false";
        try {
            String pathReal = (String) getServletContext().getRealPath("/images/fotos");
            File fUrlFotos = new File(pathReal);
            InputStream in = request.getInputStream();
            BufferedReader r = new BufferedReader(new InputStreamReader(in));
            StringBuffer buf = new StringBuffer();
            String line;

            //Read the BufferedReader out and receives String data
            while ((line = r.readLine()) != null) {
                buf.append(line);
            }

            String idObra = buf.substring(0, buf.indexOf("&&"));
            String fotoString = buf.substring(buf.indexOf("&&") + 2, buf.lastIndexOf("&&"));
            String comentarioFoto = buf.substring(buf.lastIndexOf("&&") + 2);
            if (comentarioFoto != null) {
                if(comentarioFoto.equals(""))comentarioFoto = null;
            }
            byte[] fotoByteArray = Base64.decode(fotoString);
            File fFotoTemp = File.createTempFile("fotoCelular", null);
            FileOutputStream f = new FileOutputStream(fFotoTemp);
            BufferedOutputStream bFoto = new BufferedOutputStream(f);
            bFoto.write(fotoByteArray);
            bFoto.flush();
            bFoto.close();
            f.close();
            boolean subirFoto = this.gestorFotosBean.subirFotoDesdeCelular(fUrlFotos, fFotoTemp, Integer.parseInt(idObra.trim()),comentarioFoto);
            fFotoTemp.delete();
            if (subirFoto) {
                exitoSubida = "true";
            }
            out.write(exitoSubida);
        } catch (Exception e) {
            SubirFotoAppMovilServlet.log4jArchivo(e);
            out.write(exitoSubida);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
